# -*- coding: utf-8 -*-
# @Time    : 2022/10/23 15:40
# @Author  : 限量老

#######################ModelForm###############################
import re

from django import forms
from django.core.exceptions import ValidationError

from app01 import models
from app01.utils.bootstrap样式 import BootStrapModelForm, BootStrapForm
from app01.utils.encrypt加密 import md5


class UserModelForm(BootStrapModelForm):
    name = forms.CharField(min_length=3, label='用户名',
                           widget=forms.TextInput(attrs={'class': 'form-control'}))  # 设定更多的限制,验证

    class Meta:
        model = models.UserInfo  # 引入models中UserInfo的字段
        fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart']


class PrettyModelForm(BootStrapModelForm):
    ''''''
    '''验证方法1:'''

    # mobile=forms.CharField(
    #     label='手机号',
    #     validators=[RegexValidator(r'^1[3-9]\d{9}$','手机号格式错误'),],#11位数字:r'^159[0-9]+$''
    # )#用正则表达式做限制

    class Meta:
        model = models.PrettyNum  # 引入models中PrettyNum的字段

        # fields=['mobile','price','level','status']
        fields = '__all__'  # 功能跟上面一样,取得全部字段
        # exclude=['level']#排除字段

    '''验证方法2:'''

    def clean_mobile(self):  # 钩子方法|| 格式:  clean_字段名(self)
        txt_mobile = self.cleaned_data['mobile']  # 用户输入的值
        if models.PrettyNum.objects.filter(mobile=txt_mobile).exists():  # 判断是否已存在
            raise ValidationError('手机号已存在')

        if re.match(r"^1[35678]\d{9}$", txt_mobile):
            return txt_mobile  # 验证通过就把用户输入的信息返回

        raise ValidationError('手机号格式错误')


'''''''''''''只有三个字段可以改'''''''''''''


class PrettyEditModelForm(BootStrapModelForm):
    mobile = forms.CharField(disabled=True, label='手机号')  # 锁定手机号不能修改

    class Meta:
        model = models.PrettyNum  # 引入models中PrettyNum的字段
        fields = '__all__'

    def clean_mobile(self):  # 钩子方法|| 格式:  clean_字段名(self)
        txt_mobile = self.cleaned_data['mobile']  # 用户输入的值
        # 排除当前编辑那一行的ID,
        if models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=txt_mobile).exists():  # 判断除了自己是否已存在
            raise ValidationError('手机号已存在')

        if re.match(r"^1[35678]\d{9}$", txt_mobile):
            return txt_mobile  # 验证通过就把用户输入的信息返回

        raise ValidationError('手机号格式错误')


class LoginForm(BootStrapForm):
    username = forms.CharField(label='用户名', widget=forms.TextInput, required=True)  # required=True:必填
    password = forms.CharField(label='密码', widget=forms.PasswordInput, required=True)  # required=True:必填
    code = forms.CharField(label='验证码', widget=forms.TextInput, required=True)  # required=True:必填

    # 定义验证的钩子方法:
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        return md5(pwd)


class AdminModelForm(BootStrapModelForm):
    '''
    1可以自定义字段
    2可以定制样式'''
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput)  # 自定义一个字段,样式设为***

    class Meta:
        model = models.Admin
        fields = ['username', 'password', 'confirm_password']
        widgets = {'password': forms.PasswordInput(render_value=True)}  # 把密码输入也设定为***,'render_value=True':保留原输入

    # 加密:
    def clean_password(self):
        pwd = self.cleaned_data.get('password')

        # 返回什么,此字段以后保存到数据库就是什么
        return md5(pwd)  # 返回加密后的密码

    # 确认密码:
    def clean_confirm_password(self):  # 输入框返回值"钩子"
        print(self.cleaned_data)
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))  # 把确认密码也加密
        if confirm != pwd:  # 密文比较
            raise ValidationError('密码不一致,请重新输入')

        # 返回什么,此字段以后保存到数据库就是什么
        # return confirm


class AdminEditModelForm(BootStrapModelForm):
    class Meta:
        model = models.Admin
        fields = ['username']  # 只允许编辑名字,不允许编辑密码


class AdminResetModelForm(BootStrapModelForm):
    confirm_password = forms.CharField(label='确认密码', widget=forms.PasswordInput(render_value=True))  # 自定义一个字段,样式设为***

    class Meta:
        model = models.Admin
        fields = ['password', 'confirm_password']
        widgets = {'password': forms.PasswordInput(render_value=True)}  # 把密码输入也设定为***,'render_value=True':保留原输入

    # 加密:
    def clean_password(self):
        pwd = self.cleaned_data.get('password')
        md5_pwd = md5(pwd)

        # 去数据库校验:当前密码跟新输入密码是否一致
        if models.Admin.objects.filter(id=self.instance.pk, password=md5_pwd).exists():  # 根据两个条件筛选,判断是否存在
            raise ValidationError('密码不能与之前相同')

        # 返回什么,此字段以后保存到数据库就是什么
        return md5_pwd  # 返回加密后的密码

    # 确认密码:
    def clean_confirm_password(self):  # 输入框返回值"钩子"
        print(self.cleaned_data)
        pwd = self.cleaned_data.get('password')
        confirm = md5(self.cleaned_data.get('confirm_password'))  # 把确认密码也加密
        if confirm != pwd:  # 密文比较
            raise ValidationError('密码不一致,请重新输入')


class TaskModelForm(BootStrapModelForm):
    class Meta:
        model = models.Task
        fields = '__all__'
        widgets = {
            'detail': forms.TextInput}
        # 可以把单行框变成多行框:
        # widgets={
        #     'detail':forms.Textarea
        # }


class OrderModelForm(BootStrapModelForm):
    # oid=forms.CharField(disabled=True,label='订单号')#锁定订单号不能修改
    class Meta:
        model = models.Order
        # fields='__all__'#显示全部字段
        exclude = ['oid', 'admin']  # 排序oid